
// Tooltips
function nocounts() {
	$('.no-count').tooltip({
		showURL: false,
		track: true,
		fade: 150,
		top: -40,
		left: -100
	}).css('cursor', 'pointer');
	$('#tooltip').addClass('bold');
}
function hascounts() {
	$('.count-tooltip').tooltip({
		showURL: false,
		track: true,
		fade: 150,
		top: -100,
		left: -380,
		//extraClass: "count-tooltip-wrapperr",
		bodyHandler: function () {
			$('#tooltip').addClass('count-tooltip-wrapper');
			return $(this).find('.tooltip-simpletable').clone();
		}
	}).css('cursor', 'pointer');
}

var viewModel = new function () {
    // Configs
    this.Leads = ko.observableArray([])
    if (data.LeadsourceList != null) {
        this.Leads = ko.observableArray(data.LeadsourceList);
    }
    this.PageSize = ko.observable(data.PageSize);
    this.CurrentPageIndex = ko.observable(data.TotalPages == null || data.TotalPages == 0 ? 0 : 1);
    this.MaxPageIndex = ko.observable(data.TotalPages);
    this.ColName = ko.observable("DateAdded");
    this.SortOrder = ko.observable("desc");
    this.VisibleUserColumn = ko.observable(data.VisibleUserColumn);

    this.FieldName1 = ko.observable(data.FieldName1);
    this.FieldName2 = ko.observable(data.FieldName2);

    // Calculate condition to add class
    // Fix issue in chrome
    this.LineClass = function (index, length, status) {
        if (status != "") {
            if (index == length)
                return "line new last";
            else
                return "line new";
        }
        else {
            if (index == length)
                return "line last";
            else
                return "line";
        }
    }

    // Total Records
    this.TotalLead = ko.observable(data.TotalLead);
    this.PageText = ko.computed(function () {
        var total = this.TotalLead();
        if (total == 1)
            return total + " lead found";
        else
            return total + " leads found";

    }, this);

    this.PageSizeText = ko.computed(function () {
        var pagevalue = this.PageSize().toString().replace(/\s/g, '');
        var pagesize = parseInt(pagevalue, 10);
        if (!IsNumeric(pagevalue))
            return "* Please enter a number between 1 - 100";
        else if (pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
            return "* Please enter a number between 1 - 100";
        }
        else {
            return "";
        }

    }, this);
    this.PageCurrentText = ko.computed(function () {
        var pagevalue = this.CurrentPageIndex().toString().replace(/\s/g, '');
        var pageindex = parseInt(pagevalue, 10);

        if (this.TotalLead() != 0) {
            if (!IsNumeric(this.CurrentPageIndex()) || pagevalue == "")
                return "* Please enter a number between 1 - " + this.MaxPageIndex() + " ";
            else if (pagevalue.toString() == 'NaN' || !IsNumeric(pagevalue) || pageindex < 1 || pageindex > this.MaxPageIndex()) {
                return "* Please enter a number between 1 - " + this.MaxPageIndex() + " ";
            }
            else {
                return "";
            }
        }
        return "";
    }, this);

    // Paginate
    this.PrevPage = function () {
        var page = parseInt(this.CurrentPageIndex());
        if (page > 1) {
            this.CurrentPageIndex(page - 1);
            LoadDataFromServer(0, 0);
        }
    }
    this.PrevButtonClass = ko.computed(function () {
        var page = parseInt(this.CurrentPageIndex());
        if (page > 1) {
            return "btn btn-prev-arrow prev-active";
        }
        else {
            return "btn btn-prev-arrow";
        }
    }, this);

    this.NextPage = function () {
        var page = parseInt(this.CurrentPageIndex());
        if (page < this.MaxPageIndex()) {
            this.CurrentPageIndex(page + 1);
            LoadDataFromServer(0, 0);
        }
    }
    this.NextButtonClass = ko.computed(function () {
        if (this.CurrentPageIndex() >= this.MaxPageIndex() || this.MaxPageIndex() == 1) {
            return "btn btn-next-arrow next-disabled";
        }
        else {
            return "btn btn-next-arrow";
        }
    }, this);

    this.DisableNextButton = ko.computed(function () {
        if (IsNumeric(this.CurrentPageIndex())) {
            var pageIndex = parseInt(this.CurrentPageIndex(), 10);
            var maxPage = parseInt(this.MaxPageIndex());

            if (pageIndex >= maxPage)
                return 1;
            else
                return 0;
        }
        return 0;
    }, this);

    // Load data
    function LoadDataFromServer(userid, leadid) {

        if (viewModel.Leads().length > 0) {
            var pagevalue = viewModel.PageSize().toString().replace(/\s/g, '');
            var pagesize = parseInt(pagevalue, 10);
            if (pagesize.toString() == 'NaN' || !IsNumeric(pagesize) || pagesize < 1 || pagesize > 100) {
                viewModel.PageSize(data.PageSize);
            }

            pagevalue = viewModel.CurrentPageIndex().toString().replace(/\s/g, '');
            var pageindex = parseInt(pagevalue, 10);
            if (pageindex.toString() == 'NaN' || !IsNumeric(pageindex) || pageindex < 1 || pageindex > viewModel.MaxPageIndex()) {
                viewModel.CurrentPageIndex(data.PageIndex);
            }

            if (viewModel.TotalLead() - (pagesize * (viewModel.CurrentPageIndex() - 1)) < 0) {
                viewModel.CurrentPageIndex(1);
            }

            var urlGet = "/Lead/SearchResultPaging";
            var dataGet = {
                "keyword": data.Header.Keywords,
                "field": data.Header.FieldId,
                "sortby": viewModel.ColName(),
                "sortorder": viewModel.SortOrder(),
                "pagesize": pagesize,
                "pagecurrent": pageindex,
                "userid": userid,
                "leadid": leadid
            };

            // Progress Bar
            openProcess();

            // Json Get function to retrive data from server
            // Ajax request
            // Build a list params
            // Call a request
            // Handle reponse
            $.ajax({
                type: "GET",
                url: urlGet,
                data: dataGet,
                dataType: "json",
                success: function (data, textStatus, jqXHR) {
                    if (data.Error == undefined || data.Error == null) {
                        viewModel.CurrentPageIndex(data.PageIndex);
                        viewModel.MaxPageIndex(data.TotalPages);
                        viewModel.PageSize(data.PageSize);
                        viewModel.TotalLead(data.TotalLead);
                        viewModel.Leads(data.LeadsourceList == null ? [] : data.LeadsourceList);

                        // Refresh tooltip
                        hascounts();
                        nocounts();

                        // Stop progress bar
                        hideProcess();
                        closePopup();
                    }
                    else {
                        // Stop progress bar
                        hideProcess();
                        showPopupError();
                    }
                },
                error: function (xhr, status, error) {
                    // Stop progress bar
                    hideProcess();
                    showPopupError();
                }
            });
        }
    }

    // Sort by Colum/Order
    function SetOrder(event, ColName) {
        if (this.ColName() === ColName) {
            this.SwitchSortOrder();
        } else {
            this.ColName(ColName);
            this.SortOrder("asc");
        }
        SetTHClass(ColName, event);
        LoadDataFromServer(0, 0);
    }
    this.SetOrder = SetOrder; // Set to an knockout object
    function SwitchSortOrder() {
        if (this.SortOrder() === "asc") {
            this.SortOrder("desc");
        } else {
            this.SortOrder("asc");
        }
    }
    this.SwitchSortOrder = SwitchSortOrder;

    function SetTHClass(colName, event) {
        $("div.title").parent().find(".sort_wrapper").children("span").removeClass("asc");
        $("div.title").parent().find(".sort_wrapper").children("span").removeClass("desc");

        if (viewModel.SortOrder() === "asc") {
            $("#" + colName).children("span").addClass("asc");
        } else {
            $("#" + colName).children("span").addClass("desc");
        }
    }

    this.UserOption = ko.observable();
    this.UserOptions = ko.observableArray(data.UserAssignFilter == null ? [] : data.UserAssignFilter);

    // Assign view lead items to user
    this.AssignToUser = function () {
        var userId = $('#userOptionSelect').editableSelect('value');
        var leadId = $('#viewleadId').val();
        if (parseInt(userId) > 0)
            LoadDataFromServer(userId, leadId);
    };

    // Delete view lead items
    this.DeleteLead = function () {
        var leadId = $('#leadId').val();
        LoadDataFromServer(0, leadId);
    };

    function LoadDataKeyPresss() {
        // Page Size
        var pageSizeValue = $('#pagesize').val().toString().replace(/\s/g, '');
        var pagesize = parseInt(pageSizeValue, 10);
        if (!IsNumeric(pageSizeValue) || pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
            return false;
        }

        // Page Index
        var pageIndexValue = $('#pagecurrent').val().toString().replace(/\s/g, '');
        var pageindex = parseInt(pageIndexValue, 10);
        if (!IsNumeric(pageIndexValue) || pageindex.toString() == 'NaN' || pageindex < 1 || pageindex > viewModel.MaxPageIndex()) {
            return false;
        }

        if (viewModel.TotalLead() - (pagesize * (viewModel.CurrentPageIndex() - 1)) < 0) {
            viewModel.CurrentPageIndex(1);
            pageindex = 1;
        }

        // Call an ajax get method
        var url = "/Lead/SearchResultPaging";
        url = url + "?keyword=" + data.Header.Keywords;
        url = url + "&field=" + data.Header.FieldId;
        url = url + "&sortby=" + viewModel.ColName();
        url = url + "&sortorder=" + viewModel.SortOrder();
        url = url + "&pagesize=" + pagesize;
        url = url + "&pagecurrent=" + pageindex;

        // progress bar
        openProcess();

        // Json Get function to retrive data from server
        $.getJSON(url, function (data) {
            viewModel.CurrentPageIndex(data.PageIndex);
            viewModel.MaxPageIndex(data.TotalPages);
            viewModel.PageSize(data.PageSize);
            viewModel.TotalLead(data.TotalLead);
            viewModel.Leads(data.LeadsourceList);

            // Refresh tooltip
            hideProcess();
            hascounts();
            nocounts();
        });
    }

    // Quick action
    this.ButtonQickAction = function (lead) {
        var dataPost = { "id": lead.Leadid };

        // Progress
        openProcess();

        // Ajax call function
        // Handle reponse
        $.ajax({
            type: "POST",
            url: "/Lead/QuickAction",
            data: dataPost,
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                // Stop progress bar
                hideProcess();

                if (data.Error == undefined || data.Error == null) {
                    window.location.href = "/Lead/SearchResult?Keyword=" + headerSearch.Keywords() + "&Field=" + headerSearch.Fields();
                }
                else {
                    showPopupError();
                }
            },
            error: function (xhr, status, error) {
                // Stop progress bar
                hideProcess();
                showPopupError();
            }
        });
    }

    // Refresh data
    this.RefreshDataByItem = function () {
        LoadDataKeyPresss();
    };
};


ko.applyBindings(viewModel, document.getElementById("main"));


function reasignOpen(leadId, userId) {
    $('#viewleadId').val(leadId);
    $('#username').text($('#user-lead' + leadId).attr("title"));

    // Reset combobox state    
    var el = $("#popup #userOptionSelect");
    if (el.length && el.editableSelect("select").length) {
        //el.editableSelect("select").get(0).selectedIndex = 0;
        $(el.editableSelect("select").get(0)).val(userId);
        el.editableSelect("refreshState");
    }

    // Show popup
    $('#popup').showPopup({
        width: 520
    });
    $('#fancybox-overlay').show();
}
function confirmPopup(leadId) {
	$('#leadId').val(leadId);
	$('#leadName').text($('#lead' + leadId).attr("rel"));

	// Show popup
	$('#confirmDelete').showPopup({
		width: 400
	});
	$('#fancybox-overlay').show();
}

function closePopup() {
	$('#popup').hide();
	$('#confirmDelete').hide();
	$('#fancybox-overlay').hide();
}

function dialIDCallPhone(leadId) {
	var phone = $('#callphone_' + leadId).attr("rel");
	var dataPost = { "leadId": leadId, "leadPhone": phone };

	// Ajax call function
	// Handle reponse
	$.ajax({
		type: "POST",
		url: "/Lead/PlaceACall",
		data: dataPost,
		dataType: "json",
		success: function (data, textStatus, jqXHR) {
			// Stop progress bar
			hideProcess();

			if (data.Error == undefined || data.Error == null) {

			}
			else {
			    showDialError();
			}
		},
		error: function (xhr, status, error) {
			// Stop progress bar
			hideProcess();
			showPopupError();
		}
	});
}

/* onload document */
$(document).ready(function () {
    $('#pagesize').removeClass('text-active');
    $('#pagecurrent').removeClass('text-active');
    $('#pagesize').data('lastValue', $('#pagesize').val());
    $('#pagecurrent').data('lastValue', $('#pagecurrent').val());

    // Key down, handle only for IE
    $('#pagesize').live('keydown', function (e) {
        var keyCode = e.keyCode || e.which;
        if (is_ie && keyCode == 13) {
            var lastValue = $('#pagesize').data('lastValue');
            var currentvalue = $('#pagesize').val().toString().replace(/\s/g, '');

            //console.log('last: ' + lastValue + ', current: ' + currentvalue);

            if (currentvalue != lastValue && lastValue != undefined) {
                var pagesize = parseInt(currentvalue, 10);

                if (!IsNumeric(currentvalue) || pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
                    //viewModel.PageSizeText("* Please enter a number between 1 - 100");
                }
                else {
                    $('#pagesize').data('lastValue', currentvalue);
                    $('#pagecurrent').val("1");

                    e.preventDefault();
                    viewModel.RefreshDataByPageSize();

                    return false;
                }
            }
            else {
                $('#pagesize').data('lastValue', currentvalue);
            }
        }
    });
    $('#pagecurrent').live('keydown', function (e) {
        var keyCode = e.keyCode || e.which;

        if (is_ie && keyCode == 13) {
            var lastValue = $('#pagecurrent').data('lastValue');
            var currentvalue = $('#pagecurrent').val().toString().replace(/\s/g, '');
            var pageindex = parseInt(currentvalue, 10);
            //console.log('last: ' + lastValue + ', current: ' + currentvalue);

            if (currentvalue != lastValue && lastValue != undefined) {
                if (!IsNumeric(currentvalue) || currentvalue == "" || currentvalue.toString() == 'NaN' || !IsNumeric(currentvalue) || pageindex < 1 || pageindex > viewModel.MaxPageIndex()) {
                    //$('#pagecurrent').data('lastValue', currentvalue);
                }
                else {
                    $('#pagecurrent').data('lastValue', currentvalue);
                    e.preventDefault();
                    // call custom function here
                    viewModel.RefreshDataByPageIndex();
                }
            }
            else {
                $('#pagecurrent').data('lastValue', currentvalue);
            }
        }
    });


    // Handle input tag blur    
    $('#pagesize').change(function (e) {
        var lastValue = $('#pagesize').data('lastValue');
        var pagevalue = $('#pagesize').val().toString().replace(/\s/g, '');
        var pagesize = parseInt(pagevalue, 10);

        if (lastValue != pagevalue) {
            if (!IsNumeric(pagevalue) || pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
                //viewModel.PageSizeText("* Please enter a number between 1 - 100");
            }
            else {
                $('#pagesize').data('lastValue', pagevalue);
                $('#pagecurrent').val("1");
                e.preventDefault();
                viewModel.RefreshDataByPageSize();
            }
        }
        else {
            $('#pagesize').data('lastValue', pagevalue);
        }
    });
    $('#pagecurrent').change(function (e) {
        var lastValue = $('#pagecurrent').data('lastValue');
        var pagevalue = $('#pagecurrent').val().toString().replace(/\s/g, '');
        var pageindex = parseInt(pagevalue, 10);

        if (lastValue != pagevalue) {
            if (!IsNumeric(pagevalue) || pagevalue == "") {
                //viewModel.PageCurrentText("* Please enter a number between 1 - " + viewModel.MaxPageIndex() + " ");
            }
            else if (pagevalue.toString() == 'NaN' || !IsNumeric(pagevalue) || pageindex < 1 || pageindex > viewModel.MaxPageIndex()) {
                //viewModel.PageCurrentText("* Please enter a number between 1 - " + viewModel.MaxPageIndex() + " ");
            }
            else {
                $('#pagecurrent').data('lastValue', pagevalue);
                e.preventDefault();
                viewModel.RefreshDataByPageIndex();
            }
        }
        else {
            $('#pagecurrent').data('lastValue', pagevalue);
        }
    });
});